package com.mycat.mq;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 消息队列消费者
 *
 * @author roger.
 * @email 190642964@qq.com
 * @create 2017-01-06
 */
public class QueueReceive {
    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;//默认连接用户名
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;//默认连接密码
    private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;//默认连接地址

    public static void main(String[] args) {
        QueueConnectionFactory queueConnectionFactory;//连接工厂
        QueueConnection queueConnection = null;//连接

        QueueSession queueSession;//会话 接受或者发送消息的线程
        Queue queue;//消息的目的地

        QueueReceiver queueReceiver;//消息的订阅者

        //实例化连接工厂
        queueConnectionFactory = new ActiveMQConnectionFactory(QueueReceive.USERNAME, QueueReceive.PASSWORD, QueueReceive.BROKEURL);

        try {
            //通过连接工厂获取连接
            queueConnection = queueConnectionFactory.createQueueConnection();
            //启动连接
            queueConnection.start();
            //创建session
            queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
            //创建一个连接HelloWorld的消息队列
            queue = queueSession.createQueue("TestPUB_SUB");
            //创建消息消费者
            queueReceiver = queueSession.createReceiver(queue);

            while (true) {
                TextMessage textMessage = (TextMessage) queueReceiver.receive(100000);

                if (textMessage != null) {
                    System.out.println("收到的消息:" + textMessage.getText() + "---------" + new SimpleDateFormat("YYYY-MM-dd HH:mm:ss.SSS").format(new Date()));
                } else {
                    break;
                }
            }
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}
